package org.chenwang.projects.ehcacheaws;

import net.sf.ehcache.Ehcache;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jets3t.service.S3ServiceException;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.multithread.S3ServiceSimpleMulti;
import org.jets3t.service.security.AWSCredentials;

public class AmazonS3CacheReplicatorImplRestSimpleMulti extends
		AmazonS3CacheReplicatorImplRestSimple {

	private static final Log log = LogFactory.getLog(AmazonS3CacheReplicatorImplRestSimpleMulti.class);

	protected S3ServiceSimpleMulti serviceMulti;
	
	public AmazonS3CacheReplicatorImplRestSimpleMulti(String bucketName,
			String pathName, String pathSeparator, AWSCredentials credentials) {
		super(bucketName, pathName, pathSeparator, credentials);
		this.initService();
	}

	protected void initService() {
		this.serviceMulti = new S3ServiceSimpleMulti(this.service);
		log.debug("initialised underlying storage service with multithreaded support");
	}

	@Override
	public Object doClone() throws CloneNotSupportedException {
		return new AmazonS3CacheReplicatorImplRestSimpleMulti(this.bucketName, 
				this.pathName, this.pathSeparator, this.credentials);
	}

	@Override
	public void notifyRemoveAll(Ehcache cache) {
		if (this.serviceMulti != null) {
			S3Object[] keys = new S3Object[cache.getKeys().size()];
			int cnt = 0;
			for (Object o : cache.getKeys()) {
				String k = this.generateKey(o);
				keys[cnt] = new S3Object(k);
				cnt ++;
			}
			log.debug("prepared all [" + keys.length + "] cache keys");
			
			try {
				this.serviceMulti.deleteObjects(new S3Bucket(this.bucketName), keys);
				log.debug("all elements removed for cache [" + cache + "]");
				
			}
			catch (S3ServiceException s3se) {
				log.fatal("error happened when removing all elements for cache [" + cache + "]!", s3se);
			}
		}
		else {
			log.warn("avoided removing all elements as underlying storage service is unavailable!");
		}
	}
	
	
}

